package com.ruoyi.common.core.utils;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.ruoyi.common.redis.service.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 短信验证码发送工具
 */
@Component
public class SmsVerificationUtils {

    private static final Logger log = LoggerFactory.getLogger(SmsVerificationUtils.class);
    /**
     * 阿里云 accessKeyId
     */
    @Value("${aliSms.accessKeyId}")
    private String accessKeyId;

    /**
     * 阿里云 secret
     */
    @Value("${aliSms.accessKeySecret}")
    private String accessKeySecret;

    /**
     * 阿里云签名
     */
    @Value("${aliSms.signName}")
    private String signName;

    /**
     * 阿里云短信模板Code
     */
    @Value("${aliSms.templateCode}")
    private String templateCode;


    @Autowired
    private RedisService redisCache;

    /**
     * 从Redis中根据手机号获取验证码
     *
     * @param key 手机号
     * @return 返回获取的验证码
     */
    public String get(String key) {
        Object code = redisCache.getCacheObject(key);
        if (code != null) {
            return redisCache.getCacheObject(key).toString();
        }
        return null;
    }

    /**
     * 删除Redis中的验证码
     *
     * @param key 手机号
     */
    public void delete(String key) {
        redisCache.deleteObject(key);
    }


    /**
     * 发送短信手机短信验证码
     *
     * @param phoneNum 手机号
     * @return 返回发送状态
     */
    public String send(String phoneNum,String uuid) {
        DefaultProfile profile = DefaultProfile.getProfile("default", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);
        Random random = new Random();
        String randomNumber = String.valueOf(100000 + random.nextInt(900000));
//        CommonRequest request = new CommonRequest();
////        request.setProtocol(ProtocolType.HTTPS);
////        request.setMethod(MethodType.POST);
////        request.setDomain("dysmsapi.aliyuncs.com");
////        request.setVersion("2017-05-25");
////        request.setAction("SendSms");
//        request.putQueryParameter("RegionId", "cn-guangzhou");
//        request.putQueryParameter("PhoneNumbers", phoneNum);
//        request.putQueryParameter("SignName", signName);
//        request.putQueryParameter("TemplateCode", templateCode);
//        request.putQueryParameter("TemplateParam", "{\"code\": " + randomNumber + "}");
//
//        try {
//
//            System.out.println("生成6位验证码为：【" + randomNumber + "】");
//            // 将验证码放入Redis缓存中  有效时间为5分钟
//            redisCache.setCacheObject(phoneNum, randomNumber, Long.parseLong("5"), TimeUnit.MINUTES);
//
////            CommonResponse response = client.getCommonResponse(request);
////            String data = response.getData();
////            return JSONObject.parseObject(data).getString("Message");
//
//            return "OK";
//        }
//        catch (ServerException e) {
//            e.printStackTrace();
//            return null;
//        }
//        catch (ClientException e) {
//            e.printStackTrace();
//            return null;
//        }
        try {
            String content ="您的登录验证码为:"+randomNumber+"。"+"任何索要验证码的都是骗子，千万别给！";
//            String sent_time = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm"));
//            int R = sendSMS(phoneNum,content,"");
            int R = 0;
            if (R>=0)
            {
            }
            else if(R==-1)
            {
                return "帐号未注册！";
            }
            else if(R==-2)
            {
                return "其他错误！";
            }
            else if(R==-3)
            {
                return "帐号或密码错误！";
            }
            else if(R==-5)
            {
                return "企业号帐户余额不足，请先充值再提交短信息！";
            }
            else if(R==-6)
            {
                return "定时发送时间不是有效时间格式！";
            }
            else if(R==-7)
            {
                return "提交信息末尾未加签名，请添加中文的企业签名【 】！";
            }

            else if(R==-8)
            {
                return "发送内容需在1到300个字之间";
            }
            else if(R==-9)
            {
                return "发送号码为空";

            }
            else if(R==-10)
            {
                return "定时时间不能小于当前系统时间！";
            }
            else if(R==-101)
            {
                return "调用接口速度太快";
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

            System.out.println("生成6位验证码为：【" + randomNumber + "】");
            // 将验证码放入Redis缓存中  有效时间为5分钟
            redisCache.setCacheObject(phoneNum+uuid, randomNumber, Long.parseLong("5"), TimeUnit.MINUTES);
            return "OK";

    }
    /*
     * 发送方法
     */
    public static int sendSMS(String Mobile,String Content,String send_time) throws MalformedURLException, UnsupportedEncodingException {
        URL url = null;
        String CorpID="LKSDK0001200";//账户名
        String Pwd="123456@";//密码
        String send_content= URLEncoder.encode(Content.replaceAll("<br/>", " "), "GBK");//发送内容
        url = new URL("https://mb345.com/ws/BatchSend2.aspx?CorpID="+CorpID+"&Pwd="+Pwd+"&Mobile="+Mobile+"&Content="+send_content+"&Cell=&SendTime="+send_time);
        BufferedReader in = null;
        int inputLine = 0;
        try {
//            System.out.println("开始发送短信手机号码为 ："+Mobile);
            in = new BufferedReader(new InputStreamReader(url.openStream()));
            inputLine = new Integer(in.readLine()).intValue();
        } catch (Exception e) {
//            System.out.println("网络异常,发送短信失败！");
            inputLine=-2;
        }
//        System.out.println("结束发送短信返回值：  "+inputLine);
        return inputLine;
    }

}
